/**
* @description: 待办工单 -》 通信设备巡视 -》 通信设备信息完善
**/
<template>
  <div class="complete-wrap">
    <nav-bar class="header" back :title="isUpdate ? '完善设备信息' : '新增设备信息'" @goBack="goBack"/>
    <van-form ref="ruleForm">
      <div class="main-container">
        <plateTitle title="基本信息" :isRequired="false" class="plate-title"/>

        <div class="base-info-container">

          <van-cell-group v-for="(item, index) in currentData.visibleProps" :key="index">

            <!-- 不可编辑框 -->
            <van-field
                v-if="item.elementType === 'TEXT'"
                :required="item.isRequired"
                readonly
                :name="item.name"
                :rules="item.rules"
                input-align="right"
                :value="item.value"
                :label="item.title"
                error-message-align="right"
                @click="checkInfo(item)"
            />
            <!-- 弹出筛选框 -->
            <van-field
                v-if="item.elementType === 'PICKER'"
                :required="item.isRequired"
                readonly
                clickable
                :name="item.name"
                :rules="item.rules"
                error-message-align="right"
                input-align="right"
                right-icon="arrow"
                v-model="item.text"
                :label="item.title"
                placeholder="点击选择"
                @click="checkPickerList(item)"
            />
            <!-- 弹出日期筛选框 -->
            <van-field
                v-if="item.elementType === 'TIMEPICKER'"
                :required="item.isRequired"
                readonly
                clickable
                :name="item.name"
                :rules="item.rules"
                error-message-align="right"
                input-align="right"
                right-icon="arrow"
                v-model="item.text"
                :label="item.title"
                placeholder="点击选择"
                @click="checkPickerList(item)"
            />
            <!-- 输入框 -->
            <van-field
                v-if="item.elementType === 'INPUT'"
                :required="item.isRequired"
                clickable
                :name="item.name"
                :rules="item.rules"
                error-message-align="right"
                input-align="right"
                :value="item.value"
                :label="item.title"
                placeholder="请输入"
                @input="inputBlur($event, item)"
            />
            <!-- 输入带扫码 -->
            <van-field
                v-if="item.elementType === 'INPUT&SCAN'"
                :required="item.isRequired"
                input-align="right"
                right-icon="scan"
                @input="inputBlur($event, item)"
                @click-right-icon="scanQrcode(item)"
                :value="item.value"
                :label="item.title"
            />

          </van-cell-group>
        </div>

        <div v-if="isUpdate && currentData.hideProps.serviceState === 4">
          <plateTitle title="巡视信息" :isRequired="false" class="plate-title-2"/>

          <!-- 巡视照片 -->
          <view class="patrol-info-container">
            <view>巡视照片</view>
            <van-divider dashed />
            <div class="image-wrap">
              <div class="image-list">
                <div
                  class="upload-button"
                  v-for="(imgItem, index) in files"
                  :style="{'background-image': `url(${imgItem.bgImg})`}"
                  @click.stop="imageHandle(imgItem, index, 'CHOOSE')"
                >
                  <div v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(imgItem, index, 'DELETE')">×</div>
                  <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgItem, index, 'PREVIEW')">
                </div>
              </div>
            </div>
          </view>


          <!-- 备注 -->
          <view class="remark-info-container">
            <view>备注</view>
            <van-divider dashed />
            <div class="remark-wrap">
          <textarea class="remark-text" v-model="currentData.otherProps.remark">
          </textarea>
            </div>
          </view>

          <view class="result-info-container">
            <van-cell-group v-for="(item, index) in currentData.tourInfoProps" :key="index">
              <!-- 不可编辑框 -->
              <van-field
                  v-if="item.elementType === 'TEXT'"
                  :required="item.isRequired"
                  readonly
                  input-align="right"
                  :value="item.value"
                  :label="item.title"
              />
            </van-cell-group>
          </view>
        </div>
      </div>
      <van-button block @click="upload">保存</van-button>
    </van-form>
    <!--选择器-->
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        ref="picker"
        :default-index="defaultPickerIndex"
        show-toolbar
        :columns="currentPickerList"
        cancel-button-text="清空"
        @confirm="pickerConfirm"
        @cancel="pickerEmpty"
        @change="pickerChange"
      />
      <van-field
          v-show="showCustomInput"
          v-model="customInput"
          placeholder="请输入"
          :border="true"
      />
    </van-popup>
    <!--时间选择器-->
    <van-popup v-model="showTimePicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="year-month"
        title="选择年月"
        :formatter="formatter"
        :min-date="minDate"
        show-toolbar
        cancel-button-text="清空"
        @confirm="pickerConfirm"
        @cancel="pickerEmpty"
      />
    </van-popup>
    <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
      <van-swipe>
        <div v-for="(image, index) in files" :key="index">
          <van-swipe-item v-if="image.img" style="text-align: center;">
            <div style="width: 100%; text-align: center;">{{ image.previewName }}</div>
            <img :src="image.img" />
          </van-swipe-item>
        </div>
      </van-swipe>
    </van-popup>
  </div>
</template>

<script>

import {Dialog, Toast} from "vant";

let infoMap_add = {


    hideProps: {
      "taskId":"task001",    //所属工单id    //必填
      "siteid": "s001",   //所属站点
      "sitename": "",   //所属站点
      "tourOperId": "2",      //巡检人ID  必填      userId放进来
      "tourOperName": "2",    //巡检人名称    必填       userName放进来
      "tourTimStr": "2022-12-19 00:00:00",   //巡检时间 必填
      "remark": "",        //备注
      "producerIdCustom": "", // 自定义设备厂家名称
      "modelnumberCustom": "" // 自定义设备型号名称
    },
    visibleProps: { // 显示的属性
      // "name": {
      //   title: "设备名称",
      //   keys: "name",
      //   value: "1#",
      //   isRequired: true,
      //   elementType: "TEXT"
      // }, //设备名称
      "sitename": {
        title: "所属站点",
        keys: "sitename",
        value: "",
        name:'sitename',
        isRequired: true,
        elementType: "TEXT",
        rules:[{ required: true, trigger:'onChange'}]
      },   //所属站点名称
      "parRoom": {
        title: "所属机房",
        keys: "parRoom",
        value: "",
        text: "",
        isRequired: false,
        elementType: "PICKER",
        optionsParams: {type: "room"}, // 获取options需要的参数
      },   //所属机房
      "parRack": {
        title: "所属机柜编号",
        keys: "parRack",
        value: "",
        isRequired: true,
        elementType: "INPUT",
        name:'parRack',
        rules:[{ required: true, trigger:'onSubmit'}]
      },   //所属机柜编号
      "parRackScreen": {
        title: "所属机柜屏眉",
        keys: "parRackScreen",
        value: "",
        isRequired: true,
        elementType: "INPUT",
        name:'parRackScreen',
        rules:[{ required: true, trigger:'onSubmit'}]

      }, //所属机柜屏眉
      "techType": {
        title: "设备类型",
        keys: "techType",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "type"}, // 获取options需要的参数
        name:'techType',
        rules:[{ required: true, trigger:'onSubmit'}]
      },    //设备类型
      "equlevel": {
        title: "设备归属",
        keys: "equlevel",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "level"}, // 获取options需要的参数
        name:'equlevel',
        rules:[{ required: true, trigger:'onSubmit'}]

      },    //设备归属
      "sysId": {
        title: "所属传输系统",
        keys: "sysId",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "os"}, // 获取options需要的参数
        name:'sysId',
        rules:[{ required: true, trigger:'onSubmit'}]

      },   //所属传输系统
      "producerId": {
        title: "设备品牌",
        keys: "producerId",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "producer"}, // 获取options需要的参数
        name:'producerId',
        rules:[{ required: true, trigger:'onSubmit'}]
      },  //设备品牌
      "modelnumber": {
        title: "设备型号",
        keys: "modelnumber",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "model"}, // 获取options需要的参数
        name:'modelnumber',
        rules:[{ required: true, trigger:'onSubmit'}]

      }, //设备型号
      "serilanum": {
        title: "设备顺序",
        keys: "serilanum",
        value: "",
        text: "",
        isRequired: false,
        elementType: "PICKER",
        optionsParams: {type: "seril"}, // 获取options需要的参数

      },   //设配顺序
      "runState": {
        title: "运行状态",
        keys: "runState",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "runState"}, // 获取options需要的参数

      },   //运行状态
      "entityid": {
        title: "实物ID",
        keys: "entityid",
        value: "",
        isRequired: false,
        elementType: "INPUT&SCAN"
      },       //实物ID
      "begTim": {
        title: "投运年限",
        keys: "begTim",
        value: "",
        isRequired: false,
        elementType: "TIMEPICKER"
      },          //设备投运年限
    }
}

let infoMap_update = {
    hideProps: {
      "taskId":"task001",    //所属工单id    //必填
      "siteid": "s001",   //所属站点
      "tourOperId": "2",      //巡检人ID  必填      userId放进来
      "producerIdCustom": "", // 自定义设备厂家名称
      "modelnumberCustom": "" // 自定义设备型号名称
    },
    visibleProps: { // 显示的属性
      "name": {
        title: "设备名称",
        keys: "name",
        value: "",
        isRequired: true,
        elementType: "TEXT",
        name:'name',
        rules:[{ required: true, trigger:'onSubmit'}]
      }, //设备名称
      "sitename": {
        title: "所属站点",
        keys: "sitename",
        value: "",
        isRequired: true,
        elementType: "TEXT",
        name:'sitename',
        rules:[{ required: true, trigger:'onSubmit'}]
      },   //所属站点名称
      "parRoom": {
        title: "所属机房",
        keys: "parRoom",
        value: "",
        text: "",
        isRequired: false,
        elementType: "PICKER",
        optionsParams: {type: "room"}, // 获取options需要的参数
      },   //所属机房
      "parRack": {
        title: "所属机柜编号",
        keys: "parRack",
        value: "",
        isRequired: true,
        elementType: "INPUT",
        name:'parRack',
        rules:[{ required: true, trigger:'onSubmit'}]

      },   //所属机柜编号
      "parRackScreen": {
        title: "所属机柜屏眉",
        keys: "parRackScreen",
        value: "",
        isRequired: true,
        elementType: "INPUT",
        name:'parRackScreen',
        rules:[{ required: true, trigger:'onSubmit'}]

      }, //所属机柜屏眉
      "techType": {
        title: "设备类型",
        keys: "techType",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "type"}, // 获取options需要的参数
        name:'techType',
        rules:[{ required: true, trigger:'onSubmit'}]
      },    //设备类型
      "equlevel": {
        title: "设备归属",
        keys: "equlevel",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "level"}, // 获取options需要的参数
        name:'equlevel',
        rules:[{ required: true, trigger:'onSubmit'}]

      },    //设备归属
      "sysId": {
        title: "所属传输系统",
        keys: "sysId",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "os"}, // 获取options需要的参数
        name:'sysId',
        rules:[{ required: true, trigger:'onSubmit'}]

      },   //所属传输系统
      "producerId": {
        title: "设备品牌",
        keys: "producerId",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "producer"}, // 获取options需要的参数
        name:'producerId',
        rules:[{ required: true, trigger:'onSubmit'}]
      },  //设备品牌
      "modelnumber": {
        title: "设备型号",
        keys: "modelnumber",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "model"}, // 获取options需要的参数
        name:'modelnumber',
        rules:[{ required: true, trigger:'onSubmit'}]

      }, //设备型号
      "serilanum": {
        title: "设备顺序",
        keys: "serilanum",
        value: "",
        text: "",
        isRequired: false,
        elementType: "PICKER",
        optionsParams: {type: "seril"}, // 获取options需要的参数

      },   //设配顺序
      "runState": {
        title: "运行状态",
        keys: "runState",
        value: "",
        text: "",
        isRequired: true,
        elementType: "PICKER",
        optionsParams: {type: "runState"}, // 获取options需要的参数

      },   //运行状态
      "entityid": {
        title: "实物ID",
        keys: "entityid",
        value: "",
        isRequired: false,
        elementType: "INPUT&SCAN"
      },       //实物ID
      "begTim": {
        title: "投运年限",
        keys: "begTim",
        value: "",
        isRequired: false,
        elementType: "TIMEPICKER"
      },          //设备投运年限
    },
    tourInfoProps: { // 显示的属性。包含巡视人和巡视时间
      "tourOperName": {
        title: "巡视人",
        keys: "tourOperName",
        value: "",
        isRequired: false,
        elementType: "TEXT"
      }, //设备名称
      "tourTimStr": {
        title: "巡视时间",
        keys: "tourTimStr",
        value: "",
        isRequired: false,
        elementType: "TEXT"
      },   //所属站点名称
    },
    otherProps: {
      // 其他，如备注，照片等
      "remark": "",        //备注
    }
}

let fileTemplate = [
  {
    name: "EQUIPMENT.jpg",
    previewName: "设备照片",
    type: "EQUIPMENT",
    bgImg: require("../../../../static/img/bg_shebei.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "NAMEPLATE.jpg",
    previewName: "铭牌照片",
    type: "NAMEPLATE",
    bgImg: require("../../../../static/img/bg_mingpai.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
  {
    name: "OTHER.jpg",
    previewName: "其他照片",
    type: "OTHER",
    bgImg: require("../../../../static/img/bg_qita.png"),
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
];
import config from "../../../../common/config";
import navBar from "../../../../components/common/nav-bar";
import plateTitle from '../../../../components/business/plateTitle';
import selectSite from '../../../common/selectSite';
import {mapGetters} from "vuex";
import moment from "moment";
import axios from "axios";
import { merge } from "lodash";

import wx from "../../../../static/common_js/jweixin_1.0.0";
export default {
  components: { navBar, plateTitle, selectSite },
  data() {
    return {
      currentIndex: 0,
      baseUrl: "", // 基础url
      objId: "", // 巡视设备id
      taskId: "", // 计划工单id
      taskType: "", // 巡视类型
      type:'',
      isUpdate: false,
      minDate: new Date(0),
      currentDate: "",
      showPicker: false,
      showTimePicker: false,
      showCustomInput: false, // 是否在下拉框中显示自定义输入
      customInput: '', // 下拉框中自定义输入的内容
      files: {}, // 照片map
      delList: [], // 被删除的列表，需要和后台交互
      showPreview: false,
      currentData: {}, // 当前数据，分为两种  添加和完善
      currentPickerList: [], // 当前可选的项
      currentChangeItem: '', // 当前正在修改的下拉项
      taskSiteName: '',
      taskSiteId: '',
      reTourCheck: '', // 巡视-1 重新编辑-0
      defaultPickerIndex: 0, // picker默认选中索引
    };
  },
  onLoad(options) {
    config.getOptions.then(res => {
      this.baseUrl = res.firstUrl;
    })
    this.objId = options.objId;
    this.taskId = options.taskId;
    this.taskType = options.state;
    this.taskSiteName = options.taskSiteName;
    this.taskSiteId = options.taskSiteId;
    this.type = options.type;
    this.files = JSON.parse(JSON.stringify(fileTemplate));
    if(options.type === 'add') { // 新增
      this.isUpdate = false;
      this.currentData = JSON.parse(JSON.stringify(infoMap_add));
      // this.addEquipment()
      this.currentData.hideProps = {
         // 新增业务线  taskid还未带过来，所属站点暂时不能选，
        "taskId": options.taskId,    //所属工单id    //必填
        "siteid": options.taskSiteId,   //所属站点
        "sitename": options.taskSiteName,   //所属站点name
        "tourOperId": this.userData.userId,      //巡检人ID  必填      userId放进来
        "tourOperName": this.userData.userName,    //巡检人名称    必填       userName放进来
        "tourTimStr": moment().format('YYYY-MM-DD HH:mm:ss'),   //巡检时间 必填
        "remark": "",        //备注
      }
      this.currentData.visibleProps.sitename.value = options.taskSiteName

    } else { // 完善
      this.isUpdate = true;
      this.reTourCheck = options.reTourCheck !== undefined ? options.reTourCheck : '1';
      this.currentData = JSON.parse(JSON.stringify(infoMap_update));
      this.currentData.tourInfoProps = {
        "tourOperName": {
          title: "巡视人",
          keys: "tourOperName",
          value: this.userData.userName,
          isRequired: false,
          elementType: "TEXT"
        }, //设备名称
        "tourTimStr": {
          title: "巡视时间",
          keys: "tourTimStr",
          value: moment().format('YYYY-MM-DD HH:mm:ss'),
          isRequired: false,
          elementType: "TEXT"
        },   //所属站点名称
      }
      this.$api.todoTaskApi.equipemntDetail({objId: this.objId}).then(res => {
        this.currentData.hideProps = {
          "taskId": options.taskId,    //所属工单id    //必填
          "siteid": options.taskSiteId,   //所属站点
          "sitename": options.taskSiteName,   //所属站点name
          "tourOperId": this.userData.userId,      //巡检人ID  必填      userId放进来
          "serviceState": res.data.serviceState === null ? 4 : res.data.serviceState, // 第一次巡视（serviceState===null），设备状态默认为更新（4）
          "remark": "",        //备注
        }
        Object.keys(this.currentData.visibleProps).forEach(key => {
          if (this.currentData.visibleProps[key].elementType === "PICKER"
            || this.currentData.visibleProps[key].elementType === "TIMEPICKER") {
            this.currentData.visibleProps[key].text = res.data[key];
          } else {
            this.currentData.visibleProps[key].value = res.data[key];
          }
          (key === "producerId") && (this.currentData.visibleProps[key].value = res.data.producer);
        });
        Object.keys(this.currentData.otherProps).forEach(key => {
          this.currentData.otherProps[key] = res.data[key];
        })
        this.currentData.visibleProps.sitename.value = options.taskSiteName
        this.files = this.files.map((item) => {
          return {
            ...item,
            img: res.data.photoMap[item.type] ? this.baseUrl + res.data.photoMap[item.type]: '',
          }
        })
      })
    }


  },
  computed: {
    ...mapGetters(["userData"]),
  },
  methods: {
    goBack() {
      if(this.reTourCheck === '0') {
        uni.navigateBack();
      }
      if (this.type === 'add') {
        uni.navigateTo({
          url: `/pages/workBench/todoTask/equipmentTour/equipmentTour?taskId=${this.taskId}&state=${this.taskType}&taskSiteName=${this.taskSiteName}`
        })
      } else {
        uni.navigateTo({
          url: `/pages/workBench/todoTask/equipmentTour/equipmentPatrol?objId=${this.objId}&taskSiteId=${this.taskSiteId}&state=${this.taskType}&taskId=${this.taskId}&taskSiteName=${this.taskSiteName}`
        })
      }
    },
    formatter(type, val) {
      if (type === 'year') return val + '年'
      if (type === 'month') return val + '月'
      if (type === 'day') return val + '日'
    },
    // 可以进行选择的东西，如所属站点
    checkInfo (item) {
      this.currentChangeItem = item.keys;
    },
    checkPickerList (optionItem) {
      this.currentChangeItem = optionItem.keys;
      if(optionItem.elementType === "TIMEPICKER") {
        this.currentDate = this.currentData.visibleProps[this.currentChangeItem].text !== ""
          ? new Date(this.currentData.visibleProps[this.currentChangeItem].text)
          : new Date();
        this.showTimePicker = true;
      }
      // 下拉选项不为日期类型时，获取可选列表
      else {
        this.showCustomInput = false;
        this.customInput = "";
        // 选项为设备型号时，请求传参带入设备品牌
        if(this.currentChangeItem === "modelnumber") {
          if(this.currentData.visibleProps.producerId.value === "") {
            Dialog.alert({
              message: '请先选择设备品牌',
              theme: 'round-button',
            });
            return;
          } else {
            optionItem.optionsParams.pid = this.currentData.visibleProps.producerId.value;
          }
        }

        if (this.currentChangeItem === 'parRoom') {
          optionItem.optionsParams.pid = this.currentData.hideProps.siteid;
        }
        // 获取可选列表
        this.$api.todoTaskApi.selectList_equipment(optionItem.optionsParams).then(async res => {
          await (this.showPicker = true);
          this.currentPickerList = res.data.map((item, index) => {
            if (item.TOTAL === this.currentData.visibleProps[this.currentChangeItem].text) {
              this.defaultPickerIndex = index;
              this.$refs.picker.setColumnIndex(0, index);
            }
            return {
              text: item.TOTAL,
              value: item.VALUE,
            }
          });
          // 如果选项为设备型号/设备品牌时，可自定义
          if(this.currentChangeItem === 'modelnumber' || this.currentChangeItem === 'producerId') {
            this.currentPickerList.push({
              text: '其他',
              value: 'other',
            })
            // 如果请求回来的下拉列表不包含当前表单项
            let includes = res.data.some((item, index) => {
              return item.TOTAL === this.currentData.visibleProps[this.currentChangeItem].text
            })
            if (!includes) {
              // 如果当前表单项的值为空，picker默认选中第一项
              if(this.currentData.visibleProps[this.currentChangeItem].text === '') {
                this.defaultPickerIndex = 0;
                this.$refs.picker.setColumnIndex(0, 0);
                // 如果下拉列表只有’其他‘，则显示自定义输入框
                if (this.currentPickerList.length === 1) {
                  this.showCustomInput = true;
                }
              }
              // 如果当前表单项的值不为空，picker默认选至'其他'，自定义值默认填入当前下拉项的值
              else {
                this.showCustomInput = true;
                this.defaultPickerIndex = this.currentPickerList.length - 1;
                this.$refs.picker.setColumnIndex(0, this.currentPickerList.length - 1);
                this.customInput = this.currentData.visibleProps[this.currentChangeItem].text;
              }
            }
          }
        });
      }
    },
    // picker确认选择(所有下拉)
    pickerConfirm (selectedOption) {
      if(this.currentChangeItem === "begTim") {
        this.currentData.visibleProps[this.currentChangeItem].text = moment(selectedOption).format('YYYY-MM');
        this.showTimePicker = false;
      } else {
        // 下拉列表不为空
        if(selectedOption !== undefined) {
          // 如果选择的设备品牌与上一次不同，设备型号清空
          if (this.currentChangeItem === "producerId" && selectedOption.value !== this.currentData.visibleProps.producerId.value) {
            this.currentData.visibleProps.modelnumber.text = "";
            this.currentData.visibleProps.modelnumber.value = "";
            this.currentData.hideProps.producerIdCustom = "";
            this.currentData.hideProps.modelnumberCustom = "";
          }
          // 如果选择的设备型号与上一次不同，清空自定义设备型号
          else if (this.currentChangeItem === "modelnumber" && selectedOption.value !== this.currentData.visibleProps.modelnumber.value) {
            this.currentData.hideProps.modelnumberCustom = "";
          }

          if(selectedOption.text === '其他') {
            this.currentData.visibleProps[this.currentChangeItem].value = selectedOption.value;
            this.currentData.visibleProps[this.currentChangeItem].text = this.customInput;
            this.currentData.hideProps[this.currentChangeItem + "Custom"] = this.customInput;
          } else {
            this.currentData.visibleProps[this.currentChangeItem].value = selectedOption.value;
            this.currentData.visibleProps[this.currentChangeItem].text = selectedOption.text;
          }
        }
        this.showPicker = false;
      }
    },
    // 在下拉框中改变选项
    pickerChange (curOption, curValue) {
      this.showCustomInput = curValue.text === '其他';
    },
    // 清空已选
    pickerEmpty (selectedOption) {
      if(this.currentChangeItem === "begTim") {
        this.showTimePicker = false;
        this.currentData.visibleProps[this.currentChangeItem].text = "";
      } else {
        this.showPicker = false;
        this.currentData.visibleProps[this.currentChangeItem].text = "";
        this.currentData.visibleProps[this.currentChangeItem].value = "";
        if(selectedOption !== undefined) {
          selectedOption.text = "";
          selectedOption.value = "";
        }
        // 清空设备品牌，同时清空设备型号
        if (this.currentChangeItem === "producerId") {
          this.currentData.visibleProps.modelnumber.text = "";
          this.currentData.visibleProps.modelnumber.value = "";
          this.currentData.hideProps.producerIdCustom = "";
          this.currentData.hideProps.modelnumberCustom = "";
        }
        // 清空设备型号
        else if (this.currentChangeItem === "modelnumber") {
          this.currentData.hideProps.modelnumberCustom = "";
        }
      }
    },
    // 为输入框时失去焦点采集输入值
    inputBlur (value, item) {
      this.currentChangeItem = item.keys;
      this.currentData.visibleProps[this.currentChangeItem].value = value;
    },
    // 扫码
    scanQrcode (item) {
      let _this = this
      wx.scanQRCode({
        desc:"scanQRCode desc",
        needResult: 1,
        scanType:["qrCode"],
        success:function(res){
          console.log(res.resultStr,1111)
          console.log(_this.currentData.visibleProps.entityid.value,1111)
          _this.currentData.visibleProps.entityid.value = res.resultStr
        },
        error:function(res){
          console.log("scanQRCode error",res);
        }
      });
    },
    addEquipment () {
      Toast.loading({
        duration:0,
        message: '加载中...',
        forbidClick: true,
      });
      let requestParams = {
        sysName: this.currentData.visibleProps.sysId.text,
        modelnumberName: this.currentData.visibleProps.modelnumber.text,
        serilanumName: this.currentData.visibleProps.serilanum.text,
        // name:   5/9 放入后台处理名称拼接
        //     this.currentData.visibleProps.sitename.value +
        //     this.currentData.visibleProps.sysId.text +
        //     this.currentData.visibleProps.modelnumber.text +
        //     this.currentData.visibleProps.serilanum.text,
        // 用户信息
        ...this.userData,
        ...this.currentData.hideProps,
        ...Object.values(this.currentData.visibleProps).reduce((prev, item) => {
          if(item.elementType === "TIMEPICKER") {
            prev[item.keys] = item.text;
          } else {
            prev[item.keys] = item.value;
          }
          return prev;
        }, {})
      }
      this.$api.todoTaskApi.addEquipment(requestParams).then(res => {
        Toast.clear();
        if(res.code === 0) {

          if(res.data === 2) {
            Dialog.confirm({
              message: "该设备已存在，请重新填写",
              showCancelButton: false,
            }).then(() => {});
          }

          else {
            Dialog.confirm({
              title: '新增成功',
              showCancelButton: false,
            })
              .then(() => {
                uni.navigateTo({
                  url: `/pages/workBench/todoTask/equipmentTour/equipmentTour?taskId=${this.currentData.hideProps.taskId}&state=${this.taskType}&taskSiteId=${this.taskSiteId}&taskSiteName=${this.taskSiteName}`
                })
              })
          }
        }

        else {
          Dialog.alert({
            message: '操作失败',
            theme: 'round-button',
          });
        }
      })
    },
    updateEquipment () {
      Toast.loading({
        duration:0,
        message: '加载中...',
        forbidClick: true,
      });
      let params = {
        reTourCheck: this.reTourCheck, // 巡视-1 重新编辑-0
        objId: this.objId,
        delList: this.delList,
        ...this.userData,
        ...this.currentData.hideProps,
        ...Object.values(this.currentData.visibleProps).reduce((prev, item) => {
          if(item.elementType === "TIMEPICKER") {
            prev[item.keys] = item.text;
          } else {
            prev[item.keys] = item.value;
          }
          return prev;
        }, {}),
        ...Object.values(this.currentData.tourInfoProps).reduce((prev, item) => {
          prev[item.keys] = item.value;
          return prev;
        }, {}),
        ...this.currentData.otherProps,
        sysName: this.currentData.visibleProps.sysId.text,
        modelnumberName: this.currentData.visibleProps.modelnumber.text,
        serilanumName: this.currentData.visibleProps.serilanum.text,
        // name:   5/9 放入后台处理名称拼接
        //   this.currentData.visibleProps.sitename.value +
        //   this.currentData.visibleProps.sysId.text +
        //   this.currentData.visibleProps.modelnumber.text +
        //   this.currentData.visibleProps.serilanum.text ,
      }

      let requestParams = {
        params: JSON.stringify(params),
        files: this.files,
      }
      let param = new FormData()  // 创建form对象
      this.files.forEach((file) => {
        if (file.raw) {
          param.append('files', file.raw, file.name)
        }
      });
      param.append('params', requestParams.params) // 添加form表单中其他数据
      // 添加请求头
      let config = {
        headers: {'Content-Type': 'multipart/form-data',Authorization: uni.getStorageSync('token') || ''}
      }
      let url = "";
      // #ifndef IGW
      url = "/ap/txksh/kosinManage/rest/api/taskCommEqu/checkInfoUpdate";
      // #endif
      // #ifdef IGW
      url = `${this.baseUrl}/txksh/kosinManage/rest/api/taskCommEqu/checkInfoUpdate`
      // #endif

      axios.post(url, param, config)
        .then(response => {
          Toast.clear()
          if(response.data.code === 0) {
            // 如果当前为巡视，且返回data为0，表示重复巡视
            if(this.reTourCheck === '1' && response.data.data === 0) {
              Dialog.confirm({
                message: "该设备已被巡视，请返回重试",
              }).then(() => {
                uni.navigateTo({
                  url: `/pages/workBench/todoTask/equipmentTour/equipmentTour?taskId=${this.currentData.hideProps.taskId}&state=${this.taskType}&taskSiteId=${this.taskSiteId}&taskSiteName=${this.taskSiteName}`
                });
              });
            }

            // 设备名称重复
            else if(response.data.data === 2) {
              Dialog.confirm({
                message: "该设备已存在，请重新填写",
                showCancelButton: false,
              }).then(() => {});
            }

            else {
              Dialog.confirm({
                title: '保存成功',
                showCancelButton: false,
              }).then(() => {
                uni.navigateTo({
                  url: `/pages/workBench/todoTask/equipmentTour/equipmentTour?taskId=${this.currentData.hideProps.taskId}&state=${this.taskType}&taskSiteId=${this.taskSiteId}&taskSiteName=${this.taskSiteName}`
                });
              });
            }

          }

          else {
            Dialog.alert({
              message: '操作失败',
              theme: 'round-button',
            });
          }

        })
    },

    imageHandle (imgItem, imgIndex, handleType) {
      if (handleType === 'CHOOSE') {
        this.choosePhoto(imgItem, imgIndex);
      } else if (handleType === 'PREVIEW') {
        this.showPreview = true;
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          message: `是否确认删除${imgItem.previewName}`
        })
          .then(() => {
            this.$set(this.files, imgIndex, {
              ...this.files[imgIndex],
              raw: null,
              img: ''
            })
            this.delList.includes(imgItem.type) ? null: this.delList.push(imgItem.type);
              console.log(this.delList, "delete")

          })
          .catch(() => {
            // on cancel
          })
      }
    },
    choosePhoto(imgItem, imgIndex) {
      let _this = this;
      wx.chooseImage({
        count: 3,
        sourceType: ["camera"],
        success: (chooseImageRes) => {
          wx.getLocalImgData({
            localId: chooseImageRes.localIds[0].toString(),
            success: function (res) {
                const localData = res.localData;
                let imageBase64 = '';
                if (localData.indexOf('data:image') == 0) {
                    //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                    imageBase64 = localData;
                } else {
                    //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                    //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                    imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
                }
                
                _this.$set(_this.files, imgIndex, merge(_this.files[imgIndex], {
                   raw: _this.h5_url_to_blob(imageBase64),
                   img: imageBase64
                }));

                
                if (_this.delList.includes(imgItem.type)) {
                  _this.delList = _this.delList.filter(item => {
                    if (item === imgItem.type) {
                      return false;
                    }
                    
                    return true;
                  });
                }
            }
          });
        },
        fail: (error) => {
          console.log(error);
        }
      });
    },
    h5_url_to_blob(url) {
      let arr = url.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    async upload() {
      await this.$refs.ruleForm.validate().then(() => {
        if (!this.isUpdate) {
          // 新增
          this.addEquipment()
        } else {
          // 完善
          this.updateEquipment()
        }
      }).catch(() => {
        Toast('请完善内容');
      })

    }
  },
}
</script>

<style scoped lang="scss">
.complete-wrap {
  background-color: #F8F8F8;
  .header {
    position: sticky;
    top: 0;
    z-index: 9;
  }

  .van-preview-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .van-swipe {
      width: 100%;
      height: 60%;
    }
    img {
      height: 90%;
    }
  }

  .main-container {
    //width: 100vw;
    height: calc(100vh - #{px2vh(423)});
    padding: px2vh(30) px2vw(30) 0 px2vw(30);
    overflow: auto;
    /deep/.van-field__label, /deep/.van-field__control:read-only, /deep/.van-field__body .van-field__control{
      font-size: px2vw(42);
    }



    .base-info-container, .result-info-container {
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
    }

    .result-info-container {
      margin-top: px2vh(30);
    }

    .plate-title {
      margin-top: px2vh(30);
      margin-bottom: px2vh(27);
    }

    .plate-title-2 {
      margin-top: px2vh(60);
      margin-bottom: px2vh(27);
    }

    .remark-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      margin-top: px2vh(30);
      .remark-wrap {
        background-color: #FAFAFA;
        padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
        border-radius: px2vw(20);
        .remark-text {
          height: px2vh(150);
        }
      }
    }

    .patrol-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;

      /deep/.van-radio {
        margin-right: px2vw(139.5)
      }

      .image-wrap {
        width: 100%;
        display: flex;
        img {
          width: px2vw(215);
          height: px2vw(215);
          margin-right: px2vw(40);
          border-radius: px2vw(6);
        }

        .image-list {
          width: 100%;
          display: flex;
          .upload-button {
            width: px2vw(215);
            height: px2vw(215);
            background-size: cover;
            margin-right: px2vw(40);
            position: relative;
            .delete-icon {
              position: absolute;
              top: px2vw(-20);
              right: px2vw(-20);
              width: px2vw(40);
              height: px2vw(40);
              background-color: rgba(0, 0, 0, 0.7);
              border-radius: 50%;
              color: #fff;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
        }

      }
    }
  }
  .van-button {
    margin: px2vh(60) auto;
    width: calc(100vw - #{px2vw(60)});
    height: px2vh(120);
    color: #fff;
    background-color: #417ADC;
    border: 1px solid #417ADC;
    border-radius: px2vh(60);
  }
  /deep/.van-uploader__upload-icon {
    text-align: center;
  }
  .van-popup {
    background-color: #eee;
    .van-cell {
      position: absolute;
      bottom: 0;
      border-top: 4px solid #eee;
      z-index: 3;
    }
  }
}

</style>
